package com.cf.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")  // 拦截所有请求
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uri = httpRequest.getRequestURI();

        // 放行静态资源
        if (uri.startsWith("/")||uri.startsWith("/static/") || uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".jpg") || uri.endsWith(".png") ||uri.endsWith(".html")) {
            chain.doFilter(request, response);  // 放行
            return;
        }

        // 进行其他处理，例如身份验证等
        // 如果验证失败，直接返回
        // if (authenticationFailed) {
        //     httpResponse.sendRedirect("/login");
        //     return;
        // }

        // 放行请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁
    }
}
